<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="合同编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientId">
        <!-- <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
          v-model="queryParams.clientId"
          filterable
          clearable
          placeholder="请输入客户名称"
        >
          <el-option
            v-for="(item, index) in componentList"
            :key="index"
            :label="item.entName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维保公司" prop="wbCompanyId">
        <!-- <el-input
          v-model="queryParams.wbCompayName"
          placeholder="请输入维保公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
          v-model="queryParams.wbCompanyId"
          filterable
          clearable
          placeholder="请输入维保单位"
        >
          <el-option
            v-for="(item, index) in maintainCompanyList"
            :key="index"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wb:wbContract:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wb:wbContract:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wb:wbContract:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="wbContractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="code" />
      <el-table-column label="合同名称" align="center" prop="name" />
      <el-table-column label="客户名称" align="center" prop="clientName">
        <template slot-scope="{ row }">
          {{ row.clientId | filtercComponent }}
        </template>
      </el-table-column>
      <el-table-column label="维保公司名称" align="center" prop="wbCompayName">
        <template slot-scope="{ row }">
          {{ row.wbCompanyId | filterMaintainCompany }}
        </template>
      </el-table-column>
      <el-table-column
        label="合同有效期"
        align="center"
        prop="contractValidity"
        width="120"
      >
        <template slot-scope="scope">
          <div>
            {{ parseTime(scope.row.contractValidityStart, "{y}-{m}-{d}") }}
          </div>
          <div>
            {{ parseTime(scope.row.contractValidityEnd, "{y}-{m}-{d}") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="项目维保有效期"
        align="center"
        prop="itemMaintenanceValidity"
        width="120"
      >
        <template slot-scope="scope">
          <div>
            {{
              parseTime(scope.row.itemMaintenanceValidityStart, "{y}-{m}-{d}")
            }}
          </div>
          <div>
            {{ parseTime(scope.row.itemMaintenanceValidityEnd, "{y}-{m}-{d}") }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="合同文件" align="center" prop="contractFile" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 1" style="color: #67c23a">
            {{ fomatterLabelName("contractStatus", scope.row.status) }}
          </div>
          <div v-if="scope.row.status == 2" style="color: #e6a23c">
            {{ fomatterLabelName("contractStatus", scope.row.status) }}
          </div>
          <div v-if="scope.row.status == 3" style="color: #f56c6c">
            {{ fomatterLabelName("contractStatus", scope.row.status) }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="描述" align="center" prop="remark" show-overflow-tooltip /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="queryUserOpen(scope.row)"
            v-hasPermi="['wb:wbContract:edit']"
            >查看用户</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-show="isShow == 'true'"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wb:wbContract:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-show="isShow == 'true'"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wb:wbContract:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维保合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        :inline="true"
        class="dialog-form"
      >
        <el-form-item label="合同编号" prop="code" class="form-item-row">
          <el-input
            v-model="form.code"
            placeholder="请输入合同编号，例如：DW2024100801"
          />
        </el-form-item>
        <el-form-item label="合同名称" prop="name" class="form-item-row">
          <el-input v-model="form.name" placeholder="请输入合同名" />
        </el-form-item>
        <el-form-item label="维保公司" prop="wbCompanyId">
          <!-- <el-input v-model="form.wbCompanyId" placeholder="请输入维保公司" /> -->
          <el-select
            v-model="form.wbCompanyId"
            filterable
            clearable
            placeholder="请输入维保单位"
          >
            <el-option
              v-for="(item, index) in maintainCompanyList"
              :key="index"
              :label="item.companyName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户公司名称" prop="clientId">
          <el-select
            v-model="form.clientId"
            filterable
            placeholder="客户公司名称"
          >
            <el-option
              v-for="(item, index) in componentList"
              :key="index"
              :label="item.entName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="客户列表" prop="wbContractUsers" class="form-item-row">
          <template slot="label">
            <span>客户列表</span>
            <el-button style="margin-left: 10px;" type="text"><i class="el-icon-circle-plus-outline"></i></el-button>
          </template>
          <el-table :data="form.wbContractUsers">
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="手机号" align="center" prop="phoneNumber" width="120"/>
          </el-table>
        </el-form-item> -->
        <el-form-item label="合同有效期" prop="contractValidityStart">
          <el-date-picker
            clearable
            v-model="form.contractValidityStart"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="开始日期"
          >
          </el-date-picker>

          <el-date-picker
            clearable
            v-model="form.contractValidityEnd"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="项目维保有效期"
          prop="itemMaintenanceValidityStart"
        >
          <el-date-picker
            clearable
            v-model="form.itemMaintenanceValidityStart"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="开始日期"
          >
          </el-date-picker>

          <el-date-picker
            clearable
            v-model="form.itemMaintenanceValidityEnd"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同文件" prop="contractFile">
          <file-upload v-model="form.contractFile" />
        </el-form-item>
        <!-- <el-form-item label="录入单位id" prop="enterBusiness">
          <el-input v-model="form.enterBusiness" placeholder="请输入录入单位id" />
        </el-form-item>
        <el-form-item label="录入单位" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入录入单位" />
        </el-form-item> -->
        <el-form-item label="描述" prop="remark" class="form-item-row">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改合同用户关联对话框 -->
    <el-dialog
      :title="userTitle"
      :visible.sync="isAddUser"
      width="700px"
      append-to-body
    >
      <!-- <el-form ref="addContarctUserForm" :model="addContarctUserForm" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addContarctUserForm.userName" clearable placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户手机号" prop="userPhone">
          <el-input v-model="addContarctUserForm.userPhone" clearable placeholder="请输入用户手机号" />
        </el-form-item>
      </el-form> -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleUserAdd"
            v-hasPermi="['system:user:add']"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userData.userList">
        <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="用户手机号" align="center" prop="userPhone" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUserUpdate(scope.row)"
              v-hasPermi="['system:user:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleUserDelete(scope.row)"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userData.total > 0"
        :total="userData.total"
        :page.sync="userData.queryParams.pageNum"
        :limit.sync="userData.queryParams.pageSize"
        @pagination="queryUser"
        layout="total, prev, pager, next"
        small
      />

      <el-dialog
        :title="userData.title"
        :visible.sync="userData.open"
        width="500px"
        append-to-body
      >
        <el-form
          ref="addContarctUserForm"
          :model="userData.form"
          :rules="userData.rules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="userData.form.userName"
              clearable
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="用户手机号" prop="userPhone">
            <el-input
              maxlength="11"
              minlength="11"
              v-model="userData.form.userPhone"
              clearable
              placeholder="请输入用户手机号"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
          <el-button @click="userData.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitAddUserForm">确 定</el-button> -->
        <el-button @click="isAddUser = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWbContract,
  getWbContract,
  delWbContract,
  addWbContract,
  updateWbContract,
} from "@/api/wb/wbContract";
import {
  getContarctUserList,
  getContarctUser,
  addContarctUser,
  updateContarctUser,
  delContarctUser,
} from "@/api/wb/contarctUser";
import { fomatterLabelName } from "@/utils/index.js";
import { mapGetters, mapActions } from "vuex";
export default {
  name: "WbContract",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维保合同表格数据
      wbContractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        clientId: null,
        clientName: null,
        wbCompanyId: null,
        wbCompayName: null,
        contractValidity: null,
        itemMaintenanceValidity: null,
        contractFile: null,
        enterBusiness: null,
        businessName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "合同编号不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "合同名称不能为空", trigger: "blur" },
        ],
        wbCompanyId: [
          { required: true, message: "维保公司不能为空", trigger: "blur" },
        ],
        clientId: [
          { required: true, message: "客户公司不能为空", trigger: "blur" },
        ],
        contractValidityStart: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        itemMaintenanceValidityStart: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
      },
      isAddUser: false,
      addContarctUserForm: {
        userName: "",
        userPhone: "",
      },
      addUserContractId: "",
      userData: {
        total: 0,
        userList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          contractId: null,
        },
        form: {
          id: null,
          userName: null,
          userPhone: null,
          contractId: null,
          contractValidityStart: "",
          contractValidityEnd: "",
          itemMaintenanceValidityStart: "",
          itemMaintenanceValidityEnd: "",
        },
        open: false,
        title: "",
        // 表单校验
        rules: {
          userPhone: [
            { required: true, message: "手机号不能为空", trigger: "blur" },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur",
            },
          ],
        },
      },
      editContractId: "",
      userTitle: "",
      isShow: false,
    };
  },
  created() {
    // 查询所有业主公司
    this.getCompanyList();
    // 查询所有维保公司
    this.getWbList();
    this.getList();
    this.isShow = window.localStorage.getItem("isShow");
  },
  computed: {
    ...mapGetters(["maintainCompanyList", "componentList"]),
  },
  methods: {
    fomatterLabelName,
    ...mapActions("reqSelect", ["getWbList", "getCompanyList"]),
    /** 查询维保合同列表 */
    getList() {
      this.loading = true;
      listWbContract(this.queryParams).then((response) => {
        this.wbContractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getData(type) {
      if (type == 1) {
        this.form.contractValidityStart = this.form.contractValidity[0];
        this.form.contractValidityEnd = this.form.contractValidity[1];
      } else {
        this.form.itemMaintenanceValidityStart =
          this.form.itemMaintenanceValidity[0];
        this.form.itemMaintenanceValidityEnd =
          this.form.itemMaintenanceValidity[1];
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        clientId: null,
        clientName: null,
        wbCompanyId: null,
        wbCompayName: null,
        contractValidity: null,
        itemMaintenanceValidity: null,
        contractFile: null,
        enterBusiness: null,
        businessName: null,
        status: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        wbContractUsers: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维保合同";
      if (this.maintainCompanyList.length > 0) {
        this.form.wbCompanyId = this.maintainCompanyList[0].id;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWbContract(id).then((response) => {
        this.form = response.data;
        this.form.contractValidity = [
          response.data.contractValidityStart,
          response.data.contractValidityEnd,
        ];
        this.form.itemMaintenanceValidity = [
          response.data.itemMaintenanceValidityStart,
          response.data.itemMaintenanceValidityEnd,
        ];
        this.open = true;
        this.title = "修改维保合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.maintainCompanyList.forEach((element) => {
        if (this.form.wbCompanyId == element.id) {
          this.form.wbCompayName = element.companyName;
        }
      });

      this.componentList.forEach((element) => {
        if (this.form.clientId == element.id) {
          this.form.clientName = element.entName;
        }
      });

      if (
        new Date(this.form.contractValidityStart) >
        new Date(this.form.contractValidityEnd)
      ) {
        this.$modal.msgWarning("请选择正确的合同有效期！");

        return;
      }

      if (
        new Date(this.form.itemMaintenanceValidityStart) >
        new Date(this.form.itemMaintenanceValidityEnd)
      ) {
        this.$modal.msgWarning("请选择正确的项目维保有效期！");

        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateWbContract(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWbContract(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除维保合同编号为"' + ids + '"的数据项？')
        .then(function () {
          return delWbContract(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "wb/wbContract/export",
        {
          ...this.queryParams,
        },
        `wbContract_${new Date().getTime()}.xlsx`
      );
    },
    queryUserOpen(row) {
      this.isAddUser = true;
      this.editContractId = row.id;
      this.userTitle = "合同编号：" + row.code;
      this.queryUser();
    },
    queryUser() {
      let { userList, queryParams } = this.userData;
      queryParams.contractId = this.editContractId;
      getContarctUserList({ ...queryParams }).then((res) => {
        this.$set(this.userData, "userList", res.rows);
        this.$set(this.userData, "total", res.total);
      });
    },
    // 表单重置
    userReset() {
      this.userData.form = {
        id: null,
        userName: null,
        userPhone: null,
        contractId: null,
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUserUpdate(row) {
      this.userReset();
      const id = row.id;
      getContarctUser(id).then((response) => {
        this.userData.form = response.data;
        this.userData.open = true;
        this.userData.title = "修改合同用户关联";
      });
    },
    /** 删除按钮操作 */
    handleUserDelete(row) {
      const ids = row.id;
      this.$modal
        .confirm('是否确认删除合同用户关联编号为"' + ids + '"的数据项？')
        .then(function () {
          return delContarctUser(ids);
        })
        .then(() => {
          this.queryUser();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 添加用户
    handleUserAdd() {
      this.userReset();
      this.userData.open = true;
      this.userData.title = "新增合同用户关联";
    },
    submitAddUserForm() {
      let { form } = this.userData;
      this.$refs["addContarctUserForm"].validate((valid) => {
        form.contractId = this.editContractId;
        if (valid) {
          if (form.id != null) {
            updateContarctUser(form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.userData.open = false;
              this.queryUser();
            });
          } else {
            addContarctUser(form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.userData.open = false;
              this.queryUser();
            });
          }
        }
      });
    },
  },
};
</script>
